package project3;

import java.util.List;

public class HTTPRequestResponseWorkerThread extends Thread {
	private int streamId;
	private int circuitId; // the circuit to which this thread will write the http response
	private byte[] byteListArr;
	private ProxyServerWrapper wrapper;
	
	public HTTPRequestResponseWorkerThread(byte[] byteListArr, int streamId, int circuitId, ProxyServerWrapper wrapper) {
		super();
		this.streamId = streamId;
		this.circuitId = circuitId;
		this.byteListArr = byteListArr;
		this.wrapper = wrapper;
	}

	
	public void run() {
		// send HTTP request data and wait for response from ProxyServer
		
		wrapper.handleRequest(streamId, byteListArr);
		byte [] hTTPResponse = wrapper.response(streamId);
		
		// divide HTTPResponse into cells
		// TODO: move the method to util
		List<RelayCell> cells = Util.cutByteArrayIntoCells(hTTPResponse, this.circuitId, this.streamId);
		
		System.out.println("[HTTPThread] Begin to send response back. ");
		
		for (RelayCell c : cells) {
			IntermediateRouter.sendDataBack(c, circuitId, true);
		}
		IntermediateRouter.sendDataBack(new RelayCell(circuitId, streamId, 0, (byte) 0x03, new byte[0]), circuitId, true);
	}
}
